package com.suncky.frame.base.mvvm;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.suncky.frame.http.bean.Page;
import com.suncky.frame.http.bean.Result;

/**
 * @author gl
 * @time 2021/12/8 17:12
 */
public class StateLiveData<E,P extends Page, R extends Result<E, P>> extends MutableLiveData<R> {
    private final MutableLiveData<LoadState> loadState = new MutableLiveData<>();

    public void observeState(LifecycleOwner owner, StateObserver<E, P, R> observer) {
        loadState.observe(owner, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == null) {
                    return;
                }
                switch (loadState.getState()) {
                    case LoadState.PRE_LOAD:
                        observer.onPreLoad();
                        break;
                    case LoadState.LOADING:
                        observer.onLoading();
                        break;
                    case LoadState.FINISHED:
                        observer.onLoadFinish();
                        break;
                }
            }
        });
        super.observe(owner, observer.getObserver());
    }

    public MutableLiveData<LoadState> getLoadState() {
        return loadState;
    }

    public void onPreLoad() {
        loadState.postValue(LoadState.newInstance(LoadState.PRE_LOAD));
    }

    public void onLoading() {
        loadState.postValue(LoadState.newInstance(LoadState.LOADING));
    }

    public void onLoadFinish() {
        loadState.postValue(LoadState.newInstance(LoadState.FINISHED));
    }
}
